package org.catdroid.bomba.server;

import java.sql.SQLException;
import java.util.Random;

import org.catdroid.bomba.server.bean.Bomb;
import org.catdroid.bomba.server.bean.Player;
import org.catdroid.bomba.server.bean.Players;
import org.catdroid.bomba.server.bean.Players.PlayerNotFoundException;
import org.catdroid.bomba.server.dao.PlayerDao;

public class GameManager {
	
	private static final int MINUTE=1000*60;
	
	private static boolean started=false;
	
	private static Bomb bomb;
	
	public GameManager() {

	}

	public void addPlayer(Player player) throws DuplicateIdException {
		
		Player p=null;
		try {
			p = PlayerDao.getPlayer(player.getId());
			if (p!=null) {
				throw new DuplicateIdException();
			}else{
				PlayerDao.insertPlayer(player);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Players getPlayers() {
		Players players=null;
		try {
			players = PlayerDao.getPlayers();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return players;
	}
	
	public void setPlayerScore (String id, int score) throws PlayerNotFoundException {
		try {
			PlayerDao.setPlayerScore(id, score);
		}catch (Exception e) {
			return;
		}
	}
	public boolean isStartReady() {
		Players players=getPlayers();
		for (Player p:players) {
			if (!p.isReady()) {
				return false;
			}
		}

		return true;
	}
	
	public  boolean isStarted() {
		return started;
	}

	public  void startGame() {
		GameManager.started = true;
		Random rnd=new Random();
		Players players=getPlayers();
		String to=players.get(rnd.nextInt(players.size())).getId();
		String time= Integer.toString(MINUTE + rnd.nextInt(MINUTE));
		bomb=new Bomb("-1",to,time);
	}

	public  Bomb getBomb() {
		return bomb;
	}

	public  void setBomb(Bomb bomb) {
		GameManager.bomb = bomb;
	}

	public void resetGame() {
		started=false;
		bomb=null;
		try {
			PlayerDao.resetPlayers();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("serial")
	public class DuplicateIdException extends Exception {
		
	}
	public boolean isFinishReady() {
		Players players=getPlayers();
		for (Player p:players) {
			if (!p.isFinished()) {
				return false;
			}
		}

		return true;
	}
	public void setPlayerReady(String id) throws PlayerNotFoundException{
		Player player= getPlayers().getPlayer(id);
		player.setReady(!player.isReady());
		
		try {
			PlayerDao.setPlayerUpdate(player);
		}catch (Exception e) {
			return;
		}
	}
	
}
